<?php
/**
* @file Rssm.php
* @synopsis  用户订阅
* @author Yee, <rlk002@gmail.com>
* @version 1.0
* @date 2015-03-24 16:52:13
*/


class Rssm extends CI_Model
{
    const MC_KEY_USER_RSS_KEY = 'mc_key_user_rss_key_';
	const MC_KEY_USER_RSS_KEY_2_1 = 'mc_key_user_rss_key_2_1';
	function __construct()
	{
		parent::__construct();
	}
	//获取帖子分类
	public function get_type_list($parent_id = 0,$user_id)
	{
		//三维数组
		$this->db->select("id,thread_name,parent_id,sort");
		$this->db->from("ml_thread");
		$this->db->where("parent_id",$parent_id);
		$this->db->order_by("sort","asc");
		$result = $this->db->get()->result_array();
		$response_array = array();
		foreach ($result as $value) {
			$this->db->select("id,thread_name");
			$this->db->from("ml_thread");
			$this->db->where("parent_id",$value['id']);
			$this->db->order_by("sort","asc");
			$result_val = $this->db->get()->result_array();
			if($result_val)
			{
				$type = array();
				$type['id'] = $value['id'];
				$type['name'] = $value['thread_name'];
				$type['content'] = $this->get_type_list($value['id'],$user_id);
				$response_array[] = $type;
			}
			else
			{
				$type = array();
				$type['id'] = $value['id'];
				$type['parent_id'] = $value['parent_id'];
				//$type['sort'] = $value['sort'];
				$type['thread_name'] = $value['thread_name'];
				$rss_type_status = $this->get_rss_status(array("user_id"=>$user_id,"type_id"=>$value['id']));
				$type['rss_status'] = $rss_type_status ? "1" : "0";
				
				$response_array[] = $type;
			}
		}
		return $response_array;
		
	}

	//获取帖子分类

	public function get_rss_status($query)
	{
		$this->db->where($query);
		$result = $this->db->get("ml_userrss")->result_array();
		return $return = $result;
	}

	/**
	 * 获取我订阅的科室ID
	 * @param $user_id
	 * @return array
	 */
	public function get_rss_thread($user_id)
	{
		$key = MY_RSS_THREAD_PREFIX.$user_id;
		$ret = $this->redis->get($key);
		if(!empty($ret))
		{
			return json_decode($ret,true);
		}

		$filter = array('type' => 1, 'user_id' => $user_id);
		$result = $this->db->select('type_id')->from('ml_userrss')->where($filter)->get()->result_array();
		if (!$result) return array();
		$ret = array_column($result, 'type_id');

		$this->redis->save($key, json_encode($ret), 60 * 60 * 6);
		return $ret;
	}

	/**
	 * 获取我订阅的标签
	 * @param $user_id
	 * @return array
	 */
	public function get_rss_tag($user_id)
	{
		$key = MY_RSS_THREADTAT_PREFIX.$user_id;
		$ret = $this->redis->get($key);
		if(!empty($ret))
		{
			return json_decode($ret,true);
		}

		$filter = array('type' => 2, 'user_id' => $user_id);
		$result = $this->db->select('type_id')->from('ml_userrss')->where($filter)->get()->result_array();
		if (!$result) return array();

		$ret =  array_column($result, 'type_id');
		$this->redis->save($key, json_encode($ret), 60 * 60 * 6);
		return $ret;
	}

	/**
	 * 获取我订阅的话题
	 * @param $user_id
	 */
	public function get_rss_topic($user_id)
	{
		$key = MY_RSS_TOPIC_PREFIX.$user_id;
		$ret = $this->redis->get($key);
		if(!empty($ret))
		{
			return json_decode($ret,true);
		}

		$filter = array('type' => 3, 'user_id' => $user_id);
		$result = $this->db->select('type_id')->from('ml_userrss')->where($filter)->get()->result_array();
		if (!$result) return array();
		$ret = array_column($result, 'type_id');

		$this->redis->save($key, json_encode($ret), 60 * 60 * 6);
		return $ret;
	}

	public function get_type_list2($parent_id = 0,$user_id)
	{
		//首先获取用户订阅数组 避免多次查询
		$user_rss_array = $this->get_user_rss_array($user_id);
		//三维数组
		$threadList = $this->cache->get('threadList_'.$parent_id);
		if($threadList)
		{
			$result = $threadList;
		}
		else
		{
			$this->db->select("id,thread_name,parent_id,sort");
			$this->db->from("ml_thread");
			$this->db->where("parent_id",$parent_id);
			$this->db->order_by("sort","asc");
			$result = $this->db->get()->result_array();
			$this->cache->save('threadList_'.$parent_id,$result,7200);
		}
		$response_array = array();
		foreach ($result as $value) {
			//echo '循环开始的地方     '.time()."<br />";
			$threadSecList = $this->cache->get('threadSecList_'.$value['id']);
			if($threadSecList)
			{
				$result_val = $threadSecList;
			}
			else
			{
				$this->db->select("id,thread_name");
				$this->db->from("ml_thread");
				$this->db->where("parent_id",$value['id']);
				$this->db->order_by("sort","asc");
				$result_val = $this->db->get()->result_array();
				$this->cache->save('threadSecList_'.$value['id'],$result_val,7200);
			}
			//echo '缓存结束的地方     '.time()."     ".$parent_id."<br />";
			if($parent_id == 1 || $parent_id == 2)
			{
				$type = array();
				$type['id'] = $value['id'];
				$type['name'] = $value['thread_name'];
				$type['content'] = $this->get_type_list2($value['id'],$user_id);
				$response_array[] = $type;
			}
			else
			{
				$type = array();
				$type['id'] = $value['id'];
				$type['parent_id'] = $value['parent_id'];
				//$type['sort'] = $value['sort'];
				$type['thread_name'] = $value['thread_name'];
				$rss_type_status = in_array($value['id'], $user_rss_array);
				$type['rss_status'] = $rss_type_status ? "1" : "0";

				$response_array[] = $type;
			}
		}
		return $response_array;
	}

	public function get_user_rss_array($uid)
	{
        $mc = $this->cache->memcached;
        $key = self::MC_KEY_USER_RSS_KEY . $uid;

        $this->cache->memcached->is_supported();

		$return = array();
        $return = $mc->get($key);

        if(!$return)
        {
            $result = $this->db->select("type_id")->where("user_id",$uid)->get("ml_userrss")->result_array();

			$return = array();
            foreach ($result as $value) {
                $return[] = $value['type_id'];
            }
			if ($return) {
				$mc->save($key, $return, 24 * 60 * 60);
			}
        }
		return $return;
	}

	/**
	 * 删除用户缓存的分页数据
	 * @param int $user_id
	 * @return bool
	 */
	public function delete_cache_page_data($user_id = 0)
	{
		$key  = USER_RSS_PREFIX.$user_id.':*';
		$keys = $this->redis->keys($key);

		if (!$keys) return true;

		foreach ($keys as $v) {
			$this->redis->delete($v);
		}

		return true;
	}


	/**
	 * 获取用户订阅的帖子IDS
	 * @param $uid
	 * @param int $post_type_extend
	 * @param int $page
	 * @param int $page_size
	 * @param int $order
	 * @return array
	 */
	public function get_user_rss_array_for_2_2($uid, $post_type_extend = 100, $page = 1, $page_size = 20, $order = 0, $hate_info = array())
	{
		$post_ids = array();
		$pre_key = $uid . ':' . $post_type_extend . ':' . $page . ':' . $page_size;
		$key = USER_RSS_PREFIX.$pre_key;

		$result = $this->redis->get($key);
		if ($result) $post_ids = unserialize($result);

		if (!$post_ids) {
			$start 		= ($page - 1) * $page_size;
			$rss_thread = $this->get_rss_thread($uid);
			$rss_tag    = $this->get_rss_tag($uid);
			$tmp_thread = $rss_thread;

			// 用户没有订阅,取用户默认所在科室
			if (!$rss_thread) {
				$user_info = $this->userm->getUserInfoById($uid);
				$rss_thread = array($user_info['thread']);
			}

			// 问答投票加入订阅的话题
			if (in_array($post_type_extend, array(4,5))) {
				$topic_ids = $this->get_rss_topic($uid);
				$rss_thread = array_merge($rss_thread, $topic_ids);
			}

			$rss_thread = $rss_thread ? $rss_thread : array(-1);
			$rss_tag    = $rss_tag    ? $rss_tag    : array(-1);

			$filter = array('a.is_show' => 1, 'a.post_type <>' => 1);
			$this->db->select('a.id')->from('ml_post as a')->join('ml_posttype as b', 'a.id=b.post_id', 'left')->where($filter);

			if (in_array($post_type_extend, array(1,4,5))) {
				$this->db->where('a.post_type_extend', $post_type_extend);
			}

			$this->db->group_start()
						->group_start()
							->where('b.type', 1)
							->where_in('b.type_id', $rss_thread)
						->group_end()
						->or_group_start()
							->where('b.type', 2)
							->where_in('b.type_id', $rss_tag)
						->group_end()
					->group_end();

			if ($post_type_extend == 100) { // 品牌
				$this->db->where('a.is_pinpai', 2)->where_in('a.post_type_extend', array(1,2,3));
			} else if ($post_type_extend == 2 || $post_type_extend == 3) { // 疑难求助,快速求助
				$this->db->where_in('a.post_type_extend', array(2,3));
			} else if ($post_type_extend == 4 || $post_type_extend == 5) { // 问答投票
				$this->db->or_group_start()
						->where('a.post_type <>', 1)
						->where('a.is_show', 1)
								->where('a.post_type_extend', $post_type_extend)
								->where('a.special_qv', 1)
							->group_end();
			} else { // 其他
				$this->db->where('a.post_type_extend', $post_type_extend);
			}
			// 屏蔽用户及帖子
			if ($hate_info['hate_ids']) {
				$this->db->where_not_in('a.id', $hate_info['hate_ids']);
			}
			if ($hate_info['hate_user']) {
				$this->db->where_not_in('a.author_id', $hate_info['hate_user']);
			}

			/**
			 * 2016-05-19 新增逻辑 没有订阅医学影像科的人 再看列表时, 要把 医学影像科的人 发布到了 医学影响科 的帖子 （非问答投票） 过滤掉
			 */
			/*if (!in_array(129, $tmp_thread) && !in_array($post_type_extend, array(4,5))) { // 没有订阅医学影像科的人 看非 问答投票
				$this->db->where('a.special_post <>', 1);
			}*/


			// 特殊需求处理(在骨科、心内科、神经内科、普通外科、呼吸内科、肿瘤科、神经外科，影像科的病例不展示)

			if (!in_array(129, $tmp_thread) && !in_array($post_type_extend, array(4, 5))) {
				if (in_array(106, $tmp_thread) || in_array(102, $tmp_thread) || in_array(110, $tmp_thread) || in_array(95, $tmp_thread) || in_array(113, $tmp_thread)) {
					$this->db->where('a.special_post <>', 1);
				}
			}


			$result = $this->db
				->order_by('b.post_id', 'DESC')
				->group_by('b.post_id')
				->limit($page_size, $start)
				->get()
				->result_array();

			if (!$result) return array();

			$post_ids = array_column($result, 'id');
			$post_ids = array_unique($post_ids);
			if ($post_ids) {
				$post_ids_str = serialize($post_ids);
				$this->redis->save($key, $post_ids_str, USER_RSS_KEY_EXPIRE_TIME);
			}
		}

		return $post_ids;
	}

	/**
	 * 获取用户订阅的帖子 数量
	 * @param $uid
	 * @param int $post_type_extend
	 * @param int $page
	 * @param int $page_size
	 * @param int $order
	 * @return array
	 */
	public function get_user_rss_count_for_2_2($uid, $post_type_extend = 100)
	{
		$this->load->model('hatem');
		$hate_info = $this->hatem->get_hatelist($uid);

		$rss_thread = $this->get_rss_thread($uid);
		$rss_tag    = $this->get_rss_tag($uid);
		$tmp_thread = $rss_thread;

		// 用户没有订阅,取用户默认所在科室
		if (!$rss_thread) {
			$user_info = $this->userm->getUserInfoById($uid);
			$rss_thread = array($user_info['thread']);
		}

		// 问答投票加入订阅的话题
		if (in_array($post_type_extend, array(4,5))) {
			$topic_ids = $this->get_rss_topic($uid);
			$rss_thread = array_merge($rss_thread, $topic_ids);
		}

		$rss_thread = $rss_thread ? $rss_thread : array(-1);
		$rss_tag    = $rss_tag    ? $rss_tag    : array(-1);

		$filter = array('a.is_show' => 1, 'a.post_type <>' => 1);
		$this->db->select('a.id')->from('ml_post as a')->join('ml_posttype as b', 'a.id=b.post_id', 'left')->where($filter);

		if (in_array($post_type_extend, array(1,4,5))) {
			$this->db->where('a.post_type_extend', $post_type_extend);
		}

		$this->db->group_start()
			->group_start()
			->where('b.type', 1)
			->where_in('b.type_id', $rss_thread)
			->group_end()
			->or_group_start()
			->where('b.type', 2)
			->where_in('b.type_id', $rss_tag)
			->group_end()
			->group_end();

		if ($post_type_extend == 100) { // 品牌
			$this->db->where('a.is_pinpai', 2)->where_in('a.post_type_extend', array(1,2,3));
		} else if ($post_type_extend == 2 || $post_type_extend == 3) { // 疑难求助,快速求助
			$this->db->where_in('a.post_type_extend', array(2,3));
		} else if ($post_type_extend == 4 || $post_type_extend == 5) { // 问答投票
			$this->db->or_group_start()
				->where('a.post_type <>', 1)
				->where('a.is_show', 1)
				->where('a.post_type_extend', $post_type_extend)
				->where('a.special_qv', 1)
				->group_end();
		} else { // 其他
			$this->db->where('a.post_type_extend', $post_type_extend);
		}
		// 屏蔽用户及帖子
		if ($hate_info['hate_ids']) {
			$this->db->where_not_in('a.id', $hate_info['hate_ids']);
		}
		if ($hate_info['hate_user']) {
			$this->db->where_not_in('a.author_id', $hate_info['hate_user']);
		}

		/**
		 * 2016-05-19 新增逻辑 没有订阅医学影像科的人 再看列表时, 要把 医学影像科的人 发布到了 医学影响科 的帖子 （非问答投票） 过滤掉
		 */
		/*if (!in_array(129, $tmp_thread) && !in_array($post_type_extend, array(4,5))) { // 没有订阅医学影像科的人 看非 问答投票
			$this->db->where('a.special_post <>', 1);
		}*/

		if (!in_array(129, $tmp_thread) && !in_array($post_type_extend, array(4, 5))) {
			if (in_array(106, $tmp_thread) || in_array(102, $tmp_thread) || in_array(110, $tmp_thread) || in_array(95, $tmp_thread) || in_array(113, $tmp_thread)) {
				$this->db->where('a.special_post <>', 1);
			}
		}

		$count = $this->db
			->order_by('a.id', 'DESC')
			->distinct('a.id')
			->count_all_results();
		return $count;
	}


	//科室或标签品牌等列表
	public function get_qv_array_for_2_2($post_type_extend = 100, $page = 1, $page_size = 20, $type_id, $dis_cate_flag = 0)
	{
		$post_ids = array();
		$pre_key = $type_id . '-' . $dis_cate_flag . ':' . $post_type_extend . ':' . $page;
		$key = USER_RSS_PREFIX . $pre_key;

		$result = $this->redis->get($key);
		if ($result) $post_ids = unserialize($result);

		if (!$result) {
			$tmp_thread = $this->get_rss_thread($this->uid);
			#增加推荐
            $recommend_id = $this->postm->get_one_recommend($dis_cate_flag,$type_id,$post_type_extend);
            if($page == 1)
			{
				$page_size = $page_size-1;

			}

			$start = ($page - 1) * $page_size;
			$type_id = $type_id ? $type_id : -1;
			$filter = array('a.is_show' => 1);
			$this->db
					->select('a.id')
					->from('ml_post as a')
					->join('ml_posttype as b', 'a.id=b.post_id', 'left')
					->where($filter);

			$this->db->where(array('b.type' => $dis_cate_flag, 'b.type_id' => $type_id));

			if ($post_type_extend == 100) { // 品牌
				$this->db->where('a.is_pinpai', 2)->where_in('a.post_type_extend', array(1, 2, 3));
			} else if ($post_type_extend == 2 || $post_type_extend == 3) { // 疑难求助,快速求助
				$this->db->where_in('a.post_type_extend', array(2, 3));
			} else if ($post_type_extend == 4 || $post_type_extend == 5) { // 问答投票
				$this->db->group_start()
						->where('a.post_type_extend', $post_type_extend)
						->or_group_start()
						->where('a.post_type_extend', $post_type_extend)
						->where('a.special_qv', 1)
						->group_end()
						->group_end();
			} else { // 其他
				$this->db->where('a.post_type_extend', $post_type_extend);
			}
			#排重
			if($page!=1&&$recommend_id)
			{
				$this->db->where('a.id<>',$recommend_id['post_id']);
			}


			/**
			 * 2016-05-19 新增逻辑 没有订阅医学影像科的人 再看列表时, 要把 医学影像科的人 发布到了 医学影响科 的帖子 （非问答投票） 过滤掉
			 */
			/*if (!in_array(129, $tmp_thread) && !in_array($post_type_extend, array(4,5))) { // 没有订阅医学影像科的人 看非 问答投票
				$this->db->where('a.special_post <>', 1);
			}*/

			if (!in_array(129, $tmp_thread) && !in_array($post_type_extend, array(4, 5))) {
				if (in_array(106, $tmp_thread) || in_array(102, $tmp_thread) || in_array(110, $tmp_thread) || in_array(95, $tmp_thread) || in_array(113, $tmp_thread)) {
					$this->db->where('a.special_post <>', 1);
				}
			}


			$result = $this->db
					->order_by('a.id', 'DESC')
					->group_by('a.id')
					->limit($page_size, $start)
					->get()
					->result_array();

			if (!$result&&!$recommend_id) return array();

			$post_ids = array_column($result, 'id');
			if ($post_ids) {
				$post_ids_str = serialize($post_ids);
				$this->redis->save($key, $post_ids_str, USER_RSS_KEY_EXPIRE_TIME);
			}
		}
		if($page == 1&&$recommend_id)
		{
			array_unshift($post_ids,$recommend_id['post_id']);
		}
		return $post_ids;
	}


    /**
     * 添加订阅分类
     * @param $user_id
     * @param $type_id
     * @param int $type 1:科室 2:标签
     * @return object
     */
	public function add_rss($user_id, $type_id, $type = 1)
	{
		$data = array('user_id' => $user_id, 'type_id' => $type_id, 'type' => $type);
		return $this->db->insert("ml_userrss", $data);
	}


    /**
     * 订阅删除
     * @param $user_id
     * @param $type_id 自增ID
     * @param int $type 类型  1:科室 2:标签
     * @return mixed
     */
    public function del_rss($user_id, $type_id, $type = 1)
    {
        $filter = array('user_id' => $user_id, 'type_id' => $type_id, 'type' => $type);
        $this->db->where($filter)->delete("ml_userrss");
        return $this->db->affected_rows();
    }

    /**
     * 判断某个用户是否订阅某个标签,科室
     * @param $user_id
     * @param $type_id
     * @param int $type 1:科室 2:标签
     */
    public function is_rss($user_id, $type_id, $type = 1)
    {
        $filter = array('user_id' => $user_id, 'type_id' => $type_id, 'type' => $type);
        $result = $this->db->where($filter)->get('ml_userrss')->row_array();
        if ($result) return true;

        return false;
    }


	//删除订阅分类

	function reset_user_rss_cache($user_id)
	{
		$mc = $this->cache->memcached;
		$key = self::MC_KEY_USER_RSS_KEY . $user_id;

		$this->cache->memcached->is_supported();

		$mc->delete($key);

		$this->get_user_rss_array($user_id);
	}

	public function handle_rss_catefixtag($query, $action)
	{
		//首先判断之前是否订阅过
		$rss_type_status = $this->get_rss_status($query);
		if (($rss_type_status && $action == 'add') || (!$rss_type_status && $action == 'remove')) {
			$result = false;
		} else {
			if ($action == 'add') {
				$result = $this->db->insert("ml_userrss", $query);
			} else {
				$result = $this->db->where($query)->delete("ml_userrss");
			}
		}
		$this->reset_user_rss_cache($query['user_id']);
		return $result;
	}

	public function remove_rss($query)
	{

		//首先判断之前是否订阅过
		$rss_type_status = $this->get_rss_status($query);
		if ($rss_type_status) {
			$result = $this->db->where($query)->delete("ml_userrss");
		} else {
			$result = false;
		}
		$this->reset_user_rss_cache($query['user_id']);
		return $result;
	}

	/* 获取用户订阅标签及分类列表 */

	public function get_rss_list($user_id,$dis_cate_flag)
	{
		$arr = array();
		if($dis_cate_flag == 1)
		{
			$where = array('a.user_id'=>$user_id,'a.type <>'=>2);
			$arr['thread_list'] = $this->get_rss_thread_list($where);
		}
		if($dis_cate_flag == 2)
		{
			$where = array('a.user_id'=>$user_id,'a.type'=>2);
			$arr['tag_list'] = $this->get_rss_tag_list($where);
		}
		if(!$dis_cate_flag)
		{
			$where = array('a.user_id'=>$user_id,'a.type <>'=>2);
			$arr['thread_list'] = $this->get_rss_thread_list($where);
			$where = array('a.user_id'=>$user_id,'a.type'=>2);
			$arr['tag_list'] = $this->get_rss_tag_list($where);
		}
		if(!$arr)
		{
			return false;
		}

		return $arr;
	}

	/* 获取订阅分类 */
	public function get_rss_thread_list($where)
	{
		$arr = array();
		$arr = $this->db
				->select('a.user_id,a.type,b.id,b.thread_name as name, b.top_id')
				->from('ml_userrss as a')
				->join('ml_thread as b','a.type_id=b.id','left')
				->where($where)
				->where('a.type_id <>', 0)
				->order_by('b.top_id', 'ASC')
				->order_by('b.sort', 'ASC')
				->get()
				->result_array();
		if(!$arr)
		{
			return false;
		}
		return $arr;
	}
	/* 获取订阅标签 */
	public function get_rss_tag_list($where)
	{
		$arr = array();
		$arr = $this->db
				->select('a.user_id,a.type,b.id,b.tag_name as name')
				->from('ml_userrss as a')
				->join('ml_tags as b','a.type_id=b.id','left')
				->where($where)
				->where('a.type_id <>', 0)
				->get()
				->result_array();
		if(!$arr)
		{
			return false;
		}
		return $arr;
	}

	public function get_one_thread_post_ids($thread, $post_type_extend = 0)
	{
		$post_ids = array();
		$this->db
				->distinct()
				->select('a.post_id')
				->from('ml_posttype as a')
				->join('ml_post as b', 'a.post_id=b.id', 'left')
				->where(array('a.type_id' => $thread, 'a.type' => 1));
		if ($post_type_extend == 100) {
			$this->db->where('b.is_pinpai', 2);
			$this->db->where_in('b.post_type_extend', array(1, 2, 3));
		} else if (in_array($post_type_extend, array(2, 3))) {
			$this->db->where_in('b.post_type_extend', array(2, 3));
		} else {
			$this->db->where('b.post_type_extend', $post_type_extend);
		}
		$res = $this->db->get()->result_array();
		if (!$res) {
			return array();
		}
		$post_ids = array_column($res, 'post_id');
		return $post_ids;
	}

	/**
	 * 如果用户没有订阅话题分类,强制用户订阅所有话题分类
	 * @param $user_id
	 */
	public function rss_topic($user_id)
	{
		$this->config->load('thread');
		$this->load->model('threadm');
		$topic_id = $this->threadm->get_topic_ids();
		$type = $this->config->item('topic_type');

		$result = $this->db->where('user_id', $user_id)->where_in('type_id', $topic_id)->limit(1)->get('ml_userrss')->row_array();
		if (empty($result)) {
			$data = array();
			foreach($topic_id as $v) {
				$data[] = array('user_id' => $user_id, 'type_id' => $v, 'type' => $type);
			}

			$res =  $this->db->insert_batch('ml_userrss', $data);
			if ($res) {
				// 清理订阅缓存
				$this->load->model('clear_cachem');
				$this->clear_cachem->clear_user_rss($user_id);
			}

			return $res;
		}

		return false;
	}
}
